package statemachine;

/**
 * 状态机类
 * 
 * @author guweiqiang
 * 2018年7月4日
 */
public class Machine {
	
	// 机器包含的所有状态
	private State nonCoinState; // 未投币状态
	private State hasCoinState; // 已投币状态
	private State soldState; // 正在出售状态
	private State soldOutState; // 已售光状态
	
	private State state; // 机器当前状态
	private int count; // 机器中当前的糖果数量
	
	/**
	 * 初始化状态机：引入所有的状态，并初始化糖果数量
	 * @param count
	 */
	public Machine(int count) {
		this.nonCoinState = new NonCoinState(this);
		this.hasCoinState = new HasCoinState(this);
		this.soldState = new SoldState(this);
		this.soldOutState = new SoldOutState(this);
		this.count = count;
		if(this.count>0) {
			this.state = nonCoinState;
		} else {
			this.state = soldOutState;
		}
	}
	
	// 投币
	public void insertCoin() {
		this.state.insertCoin();
	}
	
	// 退回硬币
	public void ejectCoin() {
		this.state.ejectCoin();
	}
	
	// 转动摇柄
	public void turnCrank() {
		this.state.turnCrank();
		this.state.dispense();
	}
	
	// 喷出糖果的内部处理
	public void releaseBall() {
		System.out.println("喷出了1个糖果。");
		if(this.count>0) {
			this.count--;
		}
	}

	// 各个状态的get方法
	public State getNonCoinState() {
		return nonCoinState;
	}

	public State getHasCoinState() {
		return hasCoinState;
	}

	public State getSoldState() {
		return soldState;
	}

	public State getSoldOutState() {
		return soldOutState;
	}

	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}

	public int getCount() {
		return count;
	}

}
